import { Island } from '@hubspot/cms-components';
import {
  ModuleFields,
  TextField,
  BooleanField,
  ChoiceField,
  NumberField,
  ColorField,
  RichTextField,
  FieldGroup,
} from '@hubspot/cms-components/fields';
// @ts-ignore — ?island is handled by HubSpot build tooling
import FancyExampleIsland from './islands/FancyExampleIsland.tsx?island';

// ─────────────────────────────────────────────────────────────────────────────
// CSS
// ─────────────────────────────────────────────────────────────────────────────

const css = `
  @keyframes gradientShift {
    0%   { background-position: 0% 50%; }
    50%  { background-position: 100% 50%; }
    100% { background-position: 0% 50%; }
  }
  @keyframes float {
    0%, 100% { transform: translateY(0px); }
    50%       { transform: translateY(-10px); }
  }
  @keyframes pulse {
    0%, 100% { transform: scale(1); }
    50%       { transform: scale(1.1); }
  }
  @keyframes shimmer {
    0%   { background-position: -200% center; }
    100% { background-position:  200% center; }
  }
  @keyframes progressFill {
    from { width: 0%; }
    to   { width: var(--w); }
  }
  @keyframes fadeSlide {
    from { opacity: 0; transform: translateY(12px); }
    to   { opacity: 1; transform: translateY(0); }
  }

  .fe * { box-sizing: border-box; }
  .fe { font-family: system-ui, -apple-system, sans-serif; }

  /* Cards */
  .fe-card {
    background: #fff;
    border-radius: var(--fe-radius);
    padding: 20px 24px;
    box-shadow: 0 2px 16px rgba(0,0,0,0.06);
    margin-bottom: 16px;
    animation: fadeSlide 0.45s ease both;
    transition: box-shadow 0.2s, transform 0.2s;
  }
  .fe-card:hover { box-shadow: 0 6px 24px rgba(0,0,0,0.1); transform: translateY(-2px); }

  /* Hero */
  .fe-hero {
    background: linear-gradient(270deg, var(--fe-a), var(--fe-b), var(--fe-c), var(--fe-a));
    background-size: 400% 400%;
    animation: gradientShift 9s ease infinite;
    border-radius: var(--fe-radius);
    padding: 40px 32px;
    color: #fff;
    text-align: center;
    margin-bottom: 16px;
    position: relative;
    overflow: hidden;
  }
  .fe-hero::before {
    content: '';
    position: absolute; inset: 0;
    background: radial-gradient(circle at 30% 50%, rgba(255,255,255,0.15), transparent 60%);
    pointer-events: none;
  }
  .fe-hero-title { font-size: 26px; font-weight: 900; margin: 0 0 6px; text-shadow: 0 2px 8px rgba(0,0,0,0.2); }
  .fe-hero-sub   { font-size: 14px; opacity: 0.85; margin: 0; }

  /* Section label */
  .fe-label {
    font-size: 10px; font-weight: 800; letter-spacing: 1px;
    text-transform: uppercase; color: #94a3b8; margin-bottom: 12px;
  }

  /* Quote info row */
  .fe-info-row {
    display: flex; justify-content: space-between; align-items: center;
    padding: 9px 0; border-bottom: 1px solid #f1f5f9;
    font-size: 13px; color: #475569;
  }
  .fe-info-row:last-child { border-bottom: none; }
  .fe-info-val { font-weight: 600; color: #1e293b; text-align: right; max-width: 55%; word-break: break-word; }

  /* Shimmer amount */
  .fe-shimmer {
    background: linear-gradient(90deg, var(--fe-a) 20%, var(--fe-b) 50%, var(--fe-c) 80%, var(--fe-a) 100%);
    background-size: 200% auto;
    -webkit-background-clip: text; -webkit-text-fill-color: transparent;
    background-clip: text;
    animation: shimmer 2.5s linear infinite;
    font-weight: 900; font-size: 22px; display: inline-block;
  }

  /* Accordion */
  .fe-acc {
    border: 1px solid #e2e8f0; border-radius: 10px;
    margin-bottom: 8px; overflow: hidden;
    transition: box-shadow 0.2s;
  }
  .fe-acc:hover { box-shadow: 0 4px 12px rgba(0,0,0,0.06); }
  .fe-acc summary {
    list-style: none; padding: 14px 18px;
    background: #f8fafc; font-size: 13px; font-weight: 700; color: #1e293b;
    cursor: pointer; display: flex; justify-content: space-between; align-items: center;
    transition: background 0.2s;
  }
  .fe-acc summary::-webkit-details-marker { display: none; }
  .fe-acc summary:hover { background: #f1f5f9; }
  .fe-acc summary::after {
    content: '▼'; color: var(--fe-a); font-size: 11px;
    transition: transform 0.25s ease;
  }
  .fe-acc[open] summary::after { transform: rotate(180deg); }
  .fe-acc[open] summary { background: #f1f5f9; }
  .fe-acc-body {
    padding: 12px 18px 16px; font-size: 13px;
    color: #475569; line-height: 1.7; border-top: 1px solid #e2e8f0;
  }

  /* Progress bars */
  .fe-bar-wrap { margin-bottom: 12px; }
  .fe-bar-hd { display: flex; justify-content: space-between; font-size: 12px; font-weight: 600; color: #475569; margin-bottom: 5px; }
  .fe-bar-track { background: #f1f5f9; border-radius: 99px; height: 10px; overflow: hidden; }
  .fe-bar-fill {
    height: 100%; border-radius: 99px;
    animation: progressFill 1.2s ease both 0.3s;
  }

  /* CSS shapes */
  .fe-shape-a {
    width: 46px; height: 46px;
    background: linear-gradient(135deg, var(--fe-a), var(--fe-b));
    border-radius: 10px;
    animation: float 3s ease-in-out infinite;
    box-shadow: 0 8px 24px rgba(0,0,0,0.15);
  }
  .fe-shape-b {
    width: 42px; height: 42px;
    background: linear-gradient(135deg, var(--fe-b), var(--fe-c));
    clip-path: polygon(50% 0%, 100% 38%, 82% 100%, 18% 100%, 0% 38%);
    animation: float 3.5s ease-in-out infinite 0.5s;
  }
  .fe-shape-c {
    width: 38px; height: 38px;
    background: linear-gradient(135deg, var(--fe-c), var(--fe-a));
    border-radius: 50%;
    animation: pulse 2s ease-in-out infinite 1s;
    box-shadow: 0 4px 16px rgba(0,0,0,0.12);
  }

  /* Glass */
  .fe-glass {
    background: rgba(255,255,255,0.15);
    backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px);
    border: 1px solid rgba(255,255,255,0.3);
    border-radius: 12px; padding: 18px 20px;
    color: #fff; font-weight: 600;
  }
`;

// ─────────────────────────────────────────────────────────────────────────────
// Static sub-components
// ─────────────────────────────────────────────────────────────────────────────

function Bar({ label, pct, gradient }: { label: string; pct: number; gradient: string }) {
  return (
    <div className="fe-bar-wrap">
      <div className="fe-bar-hd"><span>{label}</span><span>{pct}%</span></div>
      <div className="fe-bar-track">
        <div className="fe-bar-fill" style={{ width: `${pct}%`, background: gradient, ['--w' as any]: `${pct}%` }} />
      </div>
    </div>
  );
}

function InfoRow({ label, value }: { label: string; value: string }) {
  return (
    <div className="fe-info-row">
      <span>{label}</span>
      <span className="fe-info-val">{value}</span>
    </div>
  );
}

function fmtDate(ts: number | null, locale: string): string {
  if (!ts) return '';
  return new Date(ts).toLocaleDateString(locale, { year: 'numeric', month: 'short', day: 'numeric' });
}

// ─────────────────────────────────────────────────────────────────────────────
// Component
// ─────────────────────────────────────────────────────────────────────────────

export function Component({ fieldValues, hublData }: any) {
  // ── Style fields ─────────────────────────────────────────────────────────
  const colorA = fieldValues?.styles?.colorA?.color || '#6366f1';
  const colorB = fieldValues?.styles?.colorB?.color || '#8b5cf6';
  const colorC = fieldValues?.styles?.colorC?.color || '#f472b6';
  const radius = fieldValues?.styles?.radius ?? 16;

  // ── Content fields ───────────────────────────────────────────────────────
  const title       = fieldValues?.content?.title    || 'Your Custom Quote';
  const subtitle    = fieldValues?.content?.subtitle || 'Prepared especially for you';
  const description = fieldValues?.content?.description || '';

  // ── Display toggles ──────────────────────────────────────────────────────
  const showQuoteInfo  = String(fieldValues?.display?.showQuoteInfo)  !== 'false';
  const showProgress   = String(fieldValues?.display?.showProgress)   !== 'false';
  const showDecorative = String(fieldValues?.display?.showDecorative) !== 'false';
  const showCarousel   = String(fieldValues?.display?.showCarousel)   !== 'false';
  const showApiTests   = String(fieldValues?.display?.showApiTests)   === 'true';

  // ── hublData — quote ─────────────────────────────────────────────────────
  const quoteTitle       = hublData?.quoteTitle       || null;
  const quoteNumber      = hublData?.quoteNumber      || null;
  const quoteLink        = hublData?.quoteLink        || null;
  const quoteStatus      = hublData?.quoteStatus      || null;
  const quoteProgression = hublData?.quoteProgression || null;
  const esignStatus      = hublData?.esignStatus      || null;
  const signStatus       = hublData?.signStatus       || null;
  const currency         = hublData?.currency         || '';
  const grandTotal       = hublData?.grandTotal       || null;
  const taxTotal         = hublData?.taxTotal         ?? null;
  const totalDiscount    = hublData?.totalDiscount    ?? null;
  const expirationDate   = hublData?.expirationDate   || null;
  const expired          = hublData?.expired          || false;
  const locale           = hublData?.locale           || 'en';
  const paymentStatus    = hublData?.paymentStatus    || null;
  const esignRequired    = hublData?.esignRequired    ?? null;
  const esignCompleted   = hublData?.esignCompleted   ?? null;
  const viewCount        = hublData?.viewCount        ?? null;
  const downloadCount    = hublData?.downloadCount    ?? null;
  // ── hublData — sender ────────────────────────────────────────────────────
  const senderFirstName  = hublData?.senderFirstName  || null;
  const senderLastName   = hublData?.senderLastName   || null;
  const senderEmail      = hublData?.senderEmail      || null;
  const senderCompany    = hublData?.senderCompany    || null;
  const senderDomain     = hublData?.senderDomain     || null;
  // ── hublData — deal ──────────────────────────────────────────────────────
  const dealName         = hublData?.dealName         || null;
  const dealStage        = hublData?.dealStage        || null;
  const dealAmount       = hublData?.dealAmount       || null;
  const dealCloseDate    = hublData?.dealCloseDate    || null;
  const dealCurrency     = hublData?.dealCurrency     || currency;
  // ── hublData — company ───────────────────────────────────────────────────
  const companyName      = hublData?.companyName      || null;
  const companyDomain    = hublData?.companyDomain    || null;
  const companyWebsite   = hublData?.companyWebsite   || null;
  const companyPhone     = hublData?.companyPhone     || null;
  const companyCity      = hublData?.companyCity      || null;
  const companyCountry   = hublData?.companyCountry   || null;
  const companyIndustry  = hublData?.companyIndustry  || null;
  // ── hublData — contact ───────────────────────────────────────────────────
  const contactFirstName = hublData?.contactFirstName || null;
  const contactLastName  = hublData?.contactLastName  || null;
  const contactEmail     = hublData?.contactEmail     || null;
  const contactPhone     = hublData?.contactPhone     || null;
  const contactJobTitle  = hublData?.contactJobTitle  || null;
  // ── hublData — signer ────────────────────────────────────────────────────
  const signerName       = hublData?.signerName       || null;
  const signerEmail      = hublData?.signerEmail      || null;

  const g1 = `linear-gradient(90deg, ${colorA}, ${colorB})`;
  const g2 = `linear-gradient(90deg, ${colorB}, ${colorC})`;
  const g3 = `linear-gradient(90deg, ${colorC}, ${colorA})`;

  return (
    <>
      <style dangerouslySetInnerHTML={{ __html: css }} />
      <div
        className="fe"
        style={{
          maxWidth: 740,
          margin: '0 auto',
          padding: '24px 16px',
          // CSS custom properties — drive all themed elements
          ['--fe-a' as any]: colorA,
          ['--fe-b' as any]: colorB,
          ['--fe-c' as any]: colorC,
          ['--fe-radius' as any]: `${radius}px`,
        }}
      >

        {/* ── Hero ──────────────────────────────────────────────────────── */}
        <div className="fe-hero">
          <p className="fe-hero-title">{title}</p>
          <p className="fe-hero-sub">{subtitle}</p>
          {grandTotal && (
            <div style={{ marginTop: 16 }}>
              <span className="fe-shimmer">{currency} {grandTotal}</span>
            </div>
          )}
        </div>

        {/* ── Quote info ────────────────────────────────────────────────── */}
        {showQuoteInfo && (quoteTitle || quoteNumber) && (
          <div className="fe-card">
            <div className="fe-label">Quote details</div>
            {quoteTitle       && <InfoRow label="Title"       value={quoteTitle} />}
            {quoteNumber      && <InfoRow label="Number"      value={quoteNumber} />}
            {quoteStatus      && <InfoRow label="Status"      value={quoteStatus} />}
            {quoteProgression && <InfoRow label="Progression" value={quoteProgression} />}
            {esignStatus      && <InfoRow label="eSign"       value={esignStatus} />}
            {signStatus       && <InfoRow label="Sign status" value={signStatus} />}
            {paymentStatus    && <InfoRow label="Payment"     value={paymentStatus} />}
            {expirationDate   && <InfoRow label="Expires"     value={fmtDate(expirationDate, locale) + (expired ? ' (EXPIRED)' : '')} />}
            {grandTotal != null && <InfoRow label={`Total (${currency})`}  value={String(grandTotal)} />}
            {(taxTotal ?? 0) > 0 && <InfoRow label="Tax"      value={String(taxTotal)} />}
            {(totalDiscount ?? 0) > 0 && <InfoRow label="Discount" value={String(totalDiscount)} />}
            {esignRequired != null && <InfoRow label="eSign signers" value={`${esignCompleted ?? 0} / ${esignRequired}`} />}
            {viewCount != null    && <InfoRow label="Views"    value={String(viewCount)} />}
            {downloadCount != null && <InfoRow label="Downloads" value={String(downloadCount)} />}
            {quoteLink        && <InfoRow label="Link"        value={quoteLink} />}
          </div>
        )}

        {/* ── Buyer company ─────────────────────────────────────────────── */}
        {showQuoteInfo && companyName && (
          <div className="fe-card">
            <div className="fe-label">Buyer company</div>
            {companyName    && <InfoRow label="Name"     value={companyName} />}
            {companyDomain  && <InfoRow label="Domain"   value={companyDomain} />}
            {companyWebsite && <InfoRow label="Website"  value={companyWebsite} />}
            {companyPhone   && <InfoRow label="Phone"    value={companyPhone} />}
            {(companyCity || companyCountry) && (
              <InfoRow label="Location" value={[companyCity, companyCountry].filter(Boolean).join(', ')} />
            )}
            {companyIndustry && <InfoRow label="Industry" value={companyIndustry} />}
          </div>
        )}

        {/* ── Deal ──────────────────────────────────────────────────────── */}
        {showQuoteInfo && dealName && (
          <div className="fe-card">
            <div className="fe-label">Deal</div>
            {dealName      && <InfoRow label="Name"       value={dealName} />}
            {dealStage     && <InfoRow label="Stage"      value={dealStage} />}
            {dealAmount != null && <InfoRow label={`Amount (${dealCurrency})`} value={String(dealAmount)} />}
            {dealCloseDate && <InfoRow label="Close date" value={fmtDate(dealCloseDate, locale)} />}
          </div>
        )}

        {/* ── People ────────────────────────────────────────────────────── */}
        {showQuoteInfo && (contactEmail || signerName || senderEmail) && (
          <div className="fe-card">
            <div className="fe-label">People</div>
            {(contactFirstName || contactLastName) && (
              <InfoRow label="Contact"       value={[contactFirstName, contactLastName].filter(Boolean).join(' ')} />
            )}
            {contactJobTitle && <InfoRow label="Job title"     value={contactJobTitle} />}
            {contactEmail    && <InfoRow label="Contact email" value={contactEmail} />}
            {contactPhone    && <InfoRow label="Contact phone" value={contactPhone} />}
            {signerName      && <InfoRow label="Signer"        value={signerName} />}
            {signerEmail     && <InfoRow label="Signer email"  value={signerEmail} />}
            {(senderFirstName || senderLastName) && (
              <InfoRow label="Sender"        value={[senderFirstName, senderLastName].filter(Boolean).join(' ')} />
            )}
            {senderEmail     && <InfoRow label="Sender email"  value={senderEmail} />}
            {senderCompany   && <InfoRow label="From company"  value={senderCompany} />}
            {senderDomain    && <InfoRow label="Sender domain" value={senderDomain} />}
          </div>
        )}

        {/* ── Description (RichTextField) ────────────────────────────────── */}
        {description && (
          <div className="fe-card">
            <div className="fe-label">Description</div>
            <div
              dangerouslySetInnerHTML={{ __html: description }}
              style={{ fontSize: 14, color: '#475569', lineHeight: 1.7 }}
            />
          </div>
        )}

        {/* ── Accordion terms ─────────────────────────────────────────────── */}
        {/* Rendered open by default — visible in PDF. Island can add collapse. */}
        <div className="fe-card">
          <div className="fe-label">Terms & conditions</div>
          {[
            { title: 'Payment Terms',
              body: 'Payment is due within 30 days of invoice date. Late payments are subject to a 1.5% monthly interest charge. We accept bank transfer, credit card, and SEPA direct debit.' },
            { title: 'Scope of Work',
              body: 'All deliverables will be provided digitally within the agreed timeline. Scope changes require a written change request and may affect pricing and delivery timelines.' },
            { title: 'Confidentiality',
              body: 'Both parties agree to treat all shared information as strictly confidential and not to disclose it to any third party without prior written consent for a period of 3 years.' },
            { title: 'Support & SLA',
              body: 'Priority support is included for 90 days post-delivery. Response time guaranteed within 4 business hours for critical issues during business hours (Mon–Fri, 09:00–18:00 CET).' },
          ].map((item, i) => (
            <details key={i} className="fe-acc" open>
              <summary>{item.title}</summary>
              <div className="fe-acc-body">{item.body}</div>
            </details>
          ))}
        </div>

        {/* ── Animated progress bars ─────────────────────────────────────── */}
        {showProgress && (
          <div className="fe-card">
            <div className="fe-label">Quote progress</div>
            <Bar label="Scope defined"    pct={100} gradient={g1} />
            <Bar label="Pricing approved" pct={100} gradient={g2} />
            <Bar label="Contract signed"  pct={60}  gradient={g3} />
            <Bar label="Payment received" pct={0}   gradient={g1} />
          </div>
        )}

        {/* ── Decorative: CSS animations · glassmorphism · SVG ───────────── */}
        {showDecorative && (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>

            {/* CSS animations */}
            <div className="fe-card" style={{ marginBottom: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 16 }}>
              <div className="fe-label" style={{ margin: 0 }}>CSS animations</div>
              <div style={{ display: 'flex', gap: 20, alignItems: 'center' }}>
                <div className="fe-shape-a" />
                <div className="fe-shape-b" />
                <div className="fe-shape-c" />
              </div>
            </div>

            {/* Glassmorphism */}
            <div className="fe-card" style={{ marginBottom: 0, background: `linear-gradient(135deg, ${colorA}, ${colorC})`, border: 'none' }}>
              <div className="fe-glass">
                <div style={{ fontWeight: 800, fontSize: 15, marginBottom: 4 }}>Glassmorphism</div>
                <div style={{ fontSize: 12, opacity: 0.85 }}>backdrop-filter: blur(12px)</div>
              </div>
            </div>

          </div>
        )}

        {/* Inline SVG */}
        {showDecorative && (
          <div className="fe-card">
            <div className="fe-label">Inline SVG</div>
            <svg width="100%" height="52" viewBox="0 0 400 52">
              <defs>
                <linearGradient id="feGrad" x1="0" x2="1" y1="0" y2="0">
                  <stop offset="0%"   stopColor={colorA} />
                  <stop offset="50%"  stopColor={colorB} />
                  <stop offset="100%" stopColor={colorC} />
                </linearGradient>
              </defs>
              <rect x="2" y="2" width="396" height="48" rx="10" fill="url(#feGrad)" />
              <text x="200" y="32" textAnchor="middle" fill="white" fontSize="14" fontWeight="bold">
                Inline SVG — gradient driven by STYLE tab colors
              </text>
            </svg>
          </div>
        )}

        {/* ── Island: carousel + JS API tests ───────────────────────────── */}
        {(showCarousel || showApiTests) && (
          <Island
            module={FancyExampleIsland}
            showCarousel={showCarousel}
            showApiTests={showApiTests}
            colorA={colorA}
            colorB={colorB}
            colorC={colorC}
            radius={radius}
            hydrateOn="load"
          />
        )}

      </div>
    </>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Fields
// ─────────────────────────────────────────────────────────────────────────────

export const fields = (
  <ModuleFields>

    <FieldGroup name="content" label="Content">
      <TextField
        name="title"
        label="Title"
        default="Your Custom Quote"
        helpText="Shown large in the animated hero banner"
      />
      <TextField
        name="subtitle"
        label="Subtitle"
        default="Prepared especially for you"
        helpText="Shown below the title in the hero"
      />
      <RichTextField
        name="description"
        label="Description"
        default="<p>Thank you for considering us. This quote outlines the <strong>scope, pricing, and terms</strong> of our proposal.</p>"
        helpText="Rendered below the quote info section. Supports bold, italic, links, lists."
      />
    </FieldGroup>

    <FieldGroup name="display" label="Display">
      <BooleanField
        name="showQuoteInfo"
        label="Show Quote & Company Info"
        default={true}
        helpText="Shows quote title and buyer company name pulled from the quote context"
      />
      <BooleanField
        name="showProgress"
        label="Show Progress Bars"
        default={true}
        helpText="Animated progress bars showing quote completion stages"
      />
      <BooleanField
        name="showDecorative"
        label="Show Decorative Elements"
        default={true}
        helpText="CSS animations, glassmorphism card, and inline SVG banner"
      />
      <BooleanField
        name="showCarousel"
        label="Show Carousel (Island)"
        default={true}
        helpText="Interactive package carousel — requires Island hydration, not visible in PDF"
      />
      <BooleanField
        name="showApiTests"
        label="Show JS API Tests (Island)"
        default={false}
        helpText="Canvas demo and browser API availability tests. Development use — turn off in production."
        visibility={{
          controlling_field: 'display.showCarousel',
          controlling_value_regex: 'true',
          operator: 'EQUAL',
        }}
      />
    </FieldGroup>

    <FieldGroup name="styles" label="Styles" tab="STYLE">
      <ColorField
        name="colorA"
        label="Color A (gradient start)"
        default={{ color: '#6366f1', opacity: 100 }}
        helpText="First gradient color — hero, progress bars, shapes, SVG, carousel"
      />
      <ColorField
        name="colorB"
        label="Color B (gradient mid)"
        default={{ color: '#8b5cf6', opacity: 100 }}
        helpText="Middle gradient color"
      />
      <ColorField
        name="colorC"
        label="Color C (gradient end)"
        default={{ color: '#f472b6', opacity: 100 }}
        helpText="Final gradient color"
      />
      <NumberField
        name="radius"
        label="Card Border Radius (px)"
        default={16}
        helpText="Applied to all cards and the hero banner"
      />
    </FieldGroup>

  </ModuleFields>
);

// ─────────────────────────────────────────────────────────────────────────────
// Meta
// ─────────────────────────────────────────────────────────────────────────────

export const meta = {
  label: 'Fancy Example',
  content_types: ['QUOTE', 'QUOTE_BLUEPRINT'],
};

// ─────────────────────────────────────────────────────────────────────────────
// hublData — quote context data passed to Component as a prop
// ─────────────────────────────────────────────────────────────────────────────

export const hublDataTemplate = `
  {% if quoteTemplateContext.buyerCompany %}
    {% set companyId = "" ~ quoteTemplateContext.buyerCompany.hs_object_id %}
    {% set companyDetails = crm_object(
      "company",
      companyId,
      "name,domain,website,phone,city,country,industry,numberofemployees,hs_logo_url"
    ) %}
  {% endif %}

  {% if quoteTemplateContext.buyerContacts|length > 0 %}
    {% set contact = quoteTemplateContext.buyerContacts[0] %}
  {% endif %}

  {% if quoteTemplateContext.signers|length > 0 %}
    {% set signer = quoteTemplateContext.signers[0] %}
  {% endif %}

  {% set hublData = {
    "quoteTitle":       quoteTemplateContext.quote.hs_title,
    "quoteNumber":      quoteTemplateContext.quote.hs_quote_number,
    "quoteLink":        quoteTemplateContext.quote.hs_quote_link,
    "quoteStatus":      quoteTemplateContext.quote.hs_quote_status,
    "quoteProgression": quoteTemplateContext.quote.hs_quote_progression_status,
    "esignStatus":      quoteTemplateContext.quote.hs_quote_esign_status,
    "signStatus":       quoteTemplateContext.quote.hs_sign_status,
    "currency":         quoteTemplateContext.quote.hs_currency,
    "grandTotal":       quoteTemplateContext.quote.hs_quote_amount,
    "taxTotal":         quoteTemplateContext.quote.hs_tax_total,
    "totalDiscount":    quoteTemplateContext.quote.hs_total_discount,
    "expirationDate":   quoteTemplateContext.quote.hs_expiration_date,
    "expired":          quoteTemplateContext.quote.hs_expired,
    "locale":           quoteTemplateContext.quote.hs_locale,
    "paymentStatus":    quoteTemplateContext.quote.hs_payment_status,
    "esignRequired":    quoteTemplateContext.quote.hs_esign_num_signers_required,
    "esignCompleted":   quoteTemplateContext.quote.hs_esign_num_signers_completed,
    "viewCount":        quoteTemplateContext.quote.hs_quote_view_count,
    "downloadCount":    quoteTemplateContext.quote.hs_quote_download_count,
    "senderFirstName":  quoteTemplateContext.quote.hs_sender_firstname,
    "senderLastName":   quoteTemplateContext.quote.hs_sender_lastname,
    "senderEmail":      quoteTemplateContext.quote.hs_sender_email,
    "senderImageUrl":   quoteTemplateContext.quote.hs_sender_image_url,
    "senderCompany":    quoteTemplateContext.quote.hs_sender_company_name,
    "senderDomain":     quoteTemplateContext.quote.hs_sender_company_domain,
    "dealName":         quoteTemplateContext.deal.dealname,
    "dealStage":        quoteTemplateContext.deal.dealstage,
    "dealAmount":       quoteTemplateContext.deal.amount,
    "dealCloseDate":    quoteTemplateContext.deal.closedate,
    "dealCurrency":     quoteTemplateContext.deal.deal_currency_code,
    "companyName":      companyDetails.name,
    "companyDomain":    companyDetails.domain,
    "companyWebsite":   companyDetails.website,
    "companyPhone":     companyDetails.phone,
    "companyCity":      companyDetails.city,
    "companyCountry":   companyDetails.country,
    "companyIndustry":  companyDetails.industry,
    "companyLogoUrl":   companyDetails.hs_logo_url,
    "contactFirstName": contact.firstname,
    "contactLastName":  contact.lastname,
    "contactEmail":     contact.email,
    "contactPhone":     contact.phone,
    "contactJobTitle":  contact.jobtitle,
    "signerName":       signer.name,
    "signerEmail":      signer.email,
    "signerAvatarUrl":  signer.avatarUrl
  } %}
`;
